package com.questionGenerator.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.server.HttpServerResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.questionGenerator.commom.constant.QuestionType;
import com.questionGenerator.commom.context.BaseContext;
import com.questionGenerator.commom.utils.fileSizeConvertUtil;
import com.questionGenerator.dto.req.PaperCombinationReqDTO;
import com.questionGenerator.dto.req.PaperListReqDTO;
import com.questionGenerator.dto.resp.PaperRespDTO;
import com.questionGenerator.dto.resp.QuestionRespDTO;
import com.questionGenerator.mapper.PaperMapper;
import com.questionGenerator.model.PaperDO;
import com.questionGenerator.model.QuestionDO;
import com.questionGenerator.service.PaperService;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: usagi
 * @Date: 2024/04/25/17:58
 * @Description:
 */
@Service
@Slf4j
public class PaperServiceImpl implements PaperService {
    @Autowired
    QuestionType questionType;

    @Autowired
    PaperMapper paperMapper;
    @Value("${fileDirectory}")
    String fileDirectory;
    @Override
    public Boolean paperCombination(PaperCombinationReqDTO paperCombinationReqDTO) {
        try {
            //创建一个Document类的对象
            Document document = new Document();

            //添加一个节
            Section sec = document.addSection();

            Map<Integer, List<String>> questionMap = paperCombinationReqDTO.getQuestionMap();

            questionMap.forEach((key,value)->{

                Paragraph paragraph = sec.addParagraph();
                if(!(key>questionType.getMaxNum())){
                    TextRange textRange1 = paragraph.appendText(questionType.getQuestionTypeName().get(key - questionType.getMinNum()) + "\r\n");
                    textRange1.getCharacterFormat().setBold(true);
                    textRange1.getCharacterFormat().setFontSize(20);
                    value.forEach((str)->{
                        TextRange textRange = paragraph.appendText(str+"\r\n");
                    });
                }
            });
            //添加一个段落
            //Paragraph paragraph = sec.addParagraph();
            /*
            for(int i = 0;i<20;i++){
                TextRange tr = paragraph.appendText("\r\n以下是一些文字格式设置+" + i + "：\r\n");
                if(i==0){
                    tr.getCharacterFormat().setBold(true);
                }
            }
            paragraph.getStyle().getCharacterFormat().setFontName("HarmonyOS Sans SC");
            */
            String filePath = fileDirectory+paperCombinationReqDTO.getPaperName()+".docx";
            //保存文档
            document.saveToFile(filePath, FileFormat.Docx);
            File file = new File(filePath);
            if(!file.exists()){
                log.info("打开文件失败！");
                return false;
            }
            //添加数据库文件信息
            PaperDO paperDO = PaperDO.builder().ownerName(BaseContext.getCurrentName())
                    .ownerId(String.valueOf(BaseContext.getCurrentId()))
                    .createTime(Timestamp.valueOf(LocalDateTime.now()))
                    .fileName(paperCombinationReqDTO.getPaperName())
                    .fileSize(file.length())
                    .filePath(filePath).build();
            paperMapper.insert(paperDO);

        }catch (Throwable throwable){
            System.out.println(throwable.getClass().getName()+" "+throwable.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public IPage<PaperRespDTO> getPaperListByUserId(PaperListReqDTO paperListReqDTO) {
        LambdaQueryWrapper<PaperDO> queryWrapper = Wrappers.lambdaQuery(PaperDO.class)
                .eq(PaperDO::getOwnerId,BaseContext.getCurrentId());
        Page<PaperDO> paperListReqDTO1 = paperMapper.selectPage(paperListReqDTO, queryWrapper);
        //questionRespDTOS = BeanUtil.copyToList(questionDOS, QuestionRespDTO.class).var;
        //return questionDOPage;

        return paperListReqDTO1.convert(each -> {
            PaperRespDTO result = BeanUtil.toBean(each, PaperRespDTO.class);
            result.setFileSize(fileSizeConvertUtil.convertFileSize(each.getFileSize()));
            return result;
        });
    }



    @Override
    public String downloadPaper(HttpServletResponse response, String fileName) {
        //public String fileDownLoad(HttpServletResponse response, @RequestParam("fileName") String fileName){
            String workingDirectory = System.getProperty("user.dir");
            String path = workingDirectory + fileDirectory.substring(1) + fileName + ".docx";
            File file = new File(path);
            if(!file.exists()){
                return fileName+"试卷不存在";
            }
            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.setContentLength((int) file.length());
            //需要编码
             String encode = URLEncoder.encode(fileName);
             response.setHeader("Content-Disposition", "attachment;filename=" + encode +".docx");

            try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
                byte[] buff = new byte[1024];
                OutputStream os  = response.getOutputStream();
                int i = 0;
                while ((i = bis.read(buff)) != -1) {
                    os.write(buff, 0, i);
                    os.flush();
                }
            } catch (IOException e) {
                log.error("{}",e);
                return "下载失败";
            }
            return "下载成功";
    }
    private Resource loadFileAsResource(String fileName){
        try {
            String workingDirectory = System.getProperty("user.dir");
            String path = workingDirectory + fileDirectory.substring(1) + fileName + ".docx";
            log.info(path);
            Resource resource = new UrlResource(path);
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                throw new RuntimeException("File not found: " + fileName);
            }
        } catch (IOException ex) {
            throw new RuntimeException("File not found: " + fileName, ex);
        }
    }
}
